package com.sfh.sfhshopweb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sfh.sfhshopweb.dto.WebPage;
import com.sfh.sfhshopweb.entity.Goods;
import com.sfh.sfhshopweb.entity.ToolsFile;
import com.sfh.sfhshopweb.mapper.GoodsMapper;
import com.sfh.sfhshopweb.service.IGoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sfh.sfhshopweb.service.IToolsFileService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author kcyu
 * @since 2024-06-12
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements IGoodsService {

    @Autowired
    private IToolsFileService toolsFileService;

    @Override
    public String getGoodsCoverPic(String key) {
        List<ToolsFile> toolsFiles = toolsFileService.queryFile("MA001", key);
        if(!toolsFiles.isEmpty()) {
            return toolsFiles.get(0).getUrl();
        } else {
            return null;
        }
    }

    @Override
    public List<Goods> searchGoodsByKeyword(String keyword) {
        QueryWrapper<Goods> wrapper = new QueryWrapper<>();
        wrapper.lambda().like(Goods::getName, keyword);
        List<Goods> goods = this.baseMapper.selectList(wrapper);
        goods.forEach(each -> {
            each.setCoverPic(getGoodsCoverPic(each.getPicKey()));
        });
        return goods;
    }

    @Override
    public WebPage<Goods> queryPage(WebPage<Goods> page) {
        Goods queryCondition = page.getQueryCondition();
        return lambdaQuery()
                .like(Strings.isNotEmpty(queryCondition.getName()), Goods::getName, queryCondition.getName())
                .eq(Objects.nonNull(queryCondition.getEnable()), Goods::getEnable, queryCondition.getEnable())
                .page(page);
    }

    @Override
    public Boolean deleteGoods(Long id) {
        Goods goods = this.getById(id);
        boolean b = this.removeById(id);
        if(!b) {
            return false;
        }
        try {
            List<ToolsFile> picFiles = toolsFileService.queryFile("MA001", goods.getPicKey());
            picFiles.forEach(each -> {
                toolsFileService.removeById(each.getId());
            });
        } catch (Exception e) {
            log.error("删除商品图片失败", e);
        }

        return true;

    }
}
